const net = require("net");
const fs = require("fs");
const path = require("path");
const open = require("open");
const Singleton = require("./Singleton");
const ImageRequestSocket = require("./image-socket/ImageRequestPacket");
const ImageResponseSocket = require("./image-socket/ImageResponsePacket");
const {printPacketBit} = require("./utils");
function extractParam(keyword) {
    const argv = process.argv;
    const keyword_index = argv.findIndex(item => item === keyword);
    return argv[keyword_index + 1];
}
function getImageTypeCode(image_type) {
    let imageTypes = {
        bmp: 1,
        jpeg: 2,
        gif: 3,
        png: 4,
        tiff: 5,
        raw: 15
    };
    return imageTypes[image_type.toLowerCase()];
}
function getResponseType(response_type) {
    let response_types = ['Query', 'Found', 'Not found', 'Busy'];
    return response_types[response_type];
}

Singleton.init();

let address_port = extractParam('-s');
let image_full_name = extractParam('-q');
let version = extractParam('-v');

const server_host = address_port.split(":")[0];
const server_port = address_port.split(":")[1];
const client = net.createConnection({
    host: server_host,
    port: Number(server_port)
});
const chunks = [];
client.on("connect", function () {
    console.log(`Connected to ImageDB server on: ${address_port}\n`);
    let image_file_name = image_full_name.split(".")[0];
    let image_type = image_full_name.split(".")[1];
    let p = ImageRequestSocket.build(
        Number(version),
        0,
        Singleton.getTimestamp(),
        getImageTypeCode(image_type),
        image_file_name
    );

    client.write(p);
});
client.on('data', function (chunk) {
    chunks.push(...chunk);
});
client.on('end', function () {
    console.log("console: Get image from server.");
    let data = ImageResponseSocket.parse(chunks);
    printPacketBit(chunks);
    console.log(`Server sent: 
          --ITP version = ${data.v}
          --Response Type = ${getResponseType(data.response_type)}
          --Sequence Number = ${data.sequence_number}
          --Timestamp = ${data.timestamp}\n`);
    fs.writeFileSync(path.resolve(__dirname, image_full_name), new Uint8Array(data.image_data));
    open(path.resolve(__dirname, image_full_name), {wait: true}).then(() => {
        process.exit(1);
    });
});
client.on('close', function () {
    console.log("Disconnected from the server");
    console.log("Connection closed");
});


